#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <string.h>
#include <map>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define PIPE_NAME "/tmp/car"
using namespace std;

int get_param(char*  param, map<string, string> & map_param)
{

	char  p_name[255], p_value[255];  
	int state = 1; // 1 : name start  2: value start
	int index = 0;
	for (int i = 0 ; i < strlen(param); i++)
	{
		if (param[i] == '?' || param[i] == '&')
		{
			p_value[index] = 0;
			
			map_param[p_name] = p_value;
			index = 0;
			state = 1;
		}
		else if (param[i] == '=')
		{
			p_name[index] = 0;
			index = 0;
			state = 2;
		}
		else
		{
			if (state == 1)
			{
				p_name[index] = param[i];
				index ++;
			}
			else if (state == 2)
			{
				p_value[index] = param[i];
				index ++;
			}
		}
	}
	
	map_param[p_name] = p_value;
	
}


int write_cmd_2_pipe(string& cmd)
{
	int pipe_fd = open(PIPE_NAME, O_WRONLY);
	if (pipe_fd != -1)
	{
		int ret = write(pipe_fd, cmd.c_str(), cmd.size());
		printf("cmd:%s ret:%d\n", cmd.c_str(), ret);
		if (ret<0)
		{
			return ret;
		}
	}
	else
	{
		printf("open pipe error! \n");
	}
	return 0;
}


int main(int argc, char *argv[])
{
	map<string, string> map_param;

	printf("Content-type:text/html\n\n");
	char* param;
	param = getenv("QUERY_STRING");

	get_param(param, map_param);

	map<string, string>::iterator it_p = map_param.begin();
	for(; it_p != map_param.end(); it_p ++)
	{
		printf("name:%s value:%s<br>", it_p->first.c_str(), it_p->second.c_str());
	}

	it_p = map_param.find("cmd");
	if (it_p != map_param.end())
	{
		//write the cmd to the car
		int ret;
		ret = write_cmd_2_pipe(it_p->second);
		if (ret)
		{
			printf("cmd=%s faild!", it_p->second.c_str());
		}
		else
		{
			printf("cmd=%s sucess!", it_p->second.c_str());
		}
	}

}
